/**
 * name: 联级渲染下拉框
 * author: crwoer
 * createDate: 2022/6/17
 * version: 0.20
 * notes: 基于layui架构
 */

/** 示例
<select name="grade" lay-filter="stuSub" cr-monitor="cr-select" cr-title="年级" cr-value="年级" cr-api="grades.json"></select>

crSelect({
    base: "../utils/json/",
    monitor: "cr-select",
    isRecursion: true,
    filter: "stuSub",
    onFilter: function (data) {
        console.log(data);
    },
    success(data) {
        console.log(data);
    }
})
*/

/** option
 * @param {String} base （必填）根路径
 * @param {String} monitor （必填）标签对象
 * @param {Boolean} isRecursion （选填）是否递归查询
 * @param {String} filter （选填）触发监听；当${isRecursion}为true时，必填
 * @param {Function} onFilter （选填）触发回调，配合${filter}使用
 * @param {Function} success （选填）初始成功回调
 */
/** attribute
 * @param {String} name （必填）标签名，关联请求参数
 * @param {String} cr-api （必填）请求接口
 * @param {String} cr-monitor （必填）标签对象，关联${monitor}
 * @param {String} cr-title （必填）选项标题，关联字段名
 * @param {String} cr-value （必填）选项内容，关联字段名
 * @param {String} cr-join  （选填）cr-title 或 cr-value 的拼接符
 * @param {String} lay-filter （选填）触发监听，关联${filter}
 */
layui.define(function (exports) {
    var $ = layui.$, form = layui.form;
    function crSelect(option) {
        var $selects = $("select[cr-monitor=" + option.monitor + "]");

        // 默认值
        option.isRecursion = option.isRecursion || false;

        // 初始化
        var successData = [];
        $.each($selects, function (_index, _item) {
            initSelect($(_item), {}, option.success == undefined, function (data) {
                var obj = {};
                obj[$(_item).attr("name")] = data;
                successData.push(obj);
            });
        })
        option.success && option.success(successData);

        // 触发选项
        form.on("select(" + option.filter + ")", function (event) {
            const filterOption = {
                $this: $(event.elem),
                value: event.value,
                subParams: {},
                nextSelect: { $select: undefined, data: [] }
            }

            for (i = 0; i < $selects.length; i++) {
                filterOption.subParams[$($selects[i]).attr("name")] = $($selects[i]).val()
                if (filterOption.$this.attr("name") == $($selects[i]).attr("name")) {
                    break;
                }
            }

            var $nextSelects = option.isRecursion && $(filterOption.$this.parents().nextAll().find("select[cr-monitor=" + option.monitor + "]")) || [];
            filterOption.nextSelect.$select = $nextSelects.length == 0 ? undefined : $($nextSelects[0]);
            filterOption.nextSelect.$select && initSelect(filterOption.nextSelect.$select, filterOption.subParams, false, function (data) {
                filterOption.nextSelect.data = data;
            })
            option.onFilter && option.onFilter(option.isRecursion && filterOption || {
                $this: $(event.elem),
                value: event.value,
            })
        })

        // 生成下拉框
        function initSelect($select, data = {}, async = true, callback) {
            $.ajax({
                url: option.base + $select.attr("cr-api"),
                type: "get",
                dataType: "json",
                data,
                async,
                success(res) {
                    var fiTitle = $select.attr("cr-title");
                    var fiVlaue = $select.attr("cr-value");
                    var join = $select.attr("cr-join");
                    var data = res.data || [];
                    callback && callback(data);
                    $select.empty();
                    $select.append(new Option());
                    $.each(data, function (index, item) {
                        var title = "";
                        var value = "";
                        if (join) {
                            title = fiTitle.indexOf(join) != -1 ? toJoin(item, fiTitle, join) : item[fiTitle];
                            value = fiVlaue.indexOf(join) != -1 ? toJoin(item, fiVlaue, join) : item[fiVlaue];
                        } else {
                            title = item[fiTitle];
                            value = item[fiVlaue];
                        }
                        $select.append(new Option(title, value))
                    })
                    form.render("select");
                },
                error(error) {
                    $select.empty();
                    $select.append(new Option());
                    form.render("select");
                }
            })
        }

        // 拼接title与value
        function toJoin(item, oldfiled, join) {
            var newfiled = "";
            var fileds = oldfiled && oldfiled.split(join) || [];
            var values = [];
            $.each(fileds, function (_index, _item) {
                values.push(item[_item] || "");
            })
            return values.join(join);
        }
    }
    exports('crSelect', crSelect)
})